//
//  GKLogin.swift
//  MySwiftObject
//
//  Created by anscen on 2022/5/9.
//  Copyright © 2022 wangws1990. All rights reserved.
//
import UIKit

public let loginInSuccess  = NSNotification.Name(rawValue: "loginInSuccess")
public let loginOutSuccess = NSNotification.Name(rawValue: "loginOutSuccess")

class GKLogin {
    fileprivate static let manager = GKLogin()
    fileprivate var completion :((_ success : Bool) ->())? = nil
    fileprivate var useTokenLogin : Bool = true
    fileprivate static func saveUser(_ info :GKUser){
        let defaults = UserDefaults.standard
        guard let dic = info.toJSON() else { return }
        defaults.set(dic, forKey: moya.defaultLogin)
        defaults.synchronize()
    }
    fileprivate static func deleteUser() {
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: moya.defaultLogin)
        defaults.synchronize()
        moya.user = GKUser()
    }
    public static var user :GKUser{
        get{
            let defaults = UserDefaults.standard
            let data = defaults.object(forKey:moya.defaultLogin)
            let json = JSON(data as Any)
            guard let info = GKUser.deserialize(from: json.rawString()) else { return GKUser() }
            return info
        }
    }
    public static var login : Bool{
        get{
            let vc = UIViewController.rootTopPresentedController()
            return (vc is GKLoginController)
        }
    }
    //MARK:判断是否登录
    public static var loginIn :Bool{
        get{
            return moya.user.token!.count > 0
        }
    }
    //MARK:保存用户数据模型 1、登录接口有token字段 2、获取用户信息接口无token字段
    public static func saveData(_ user :GKUser){
        moya.user = user
        saveUser(moya.user)
    }
}
extension GKLogin{
    //MARK:接口提示需要登录(服务器接口、im接口、网页webjs、这些接口能判断当前token是否有效)
    //MARK:1、当前登录已经失效
    //MARK:2、当前未登录
    public static func apiNeedLogin(needAlert :Bool = false,message :String,success:@escaping ((_ success : Bool) ->()),failure:@escaping ((_ error : String) ->())){
        if let topView = MBProgressHUD.defaultView() {
            MBProgressHUD.hide(for: topView, animated: true)
        }
        let title = GKLogin.loginIn ? "用户登录已经失效,请重新登录" : message
        if needAlert {
            let rootVC = UIViewController.rootTopPresentedController()
            if rootVC.view.viewWithTag(10086) != nil {
                return
            }
            ATAlertView.showAlertView(title: title, message: nil, normals: ["取消"], hights: ["确定"]) { title, index in
                if index > 0{
                    GKLogin.needResetTokenLogin { (finifsh) in
                        if finifsh{
                            success(finifsh)
                        }else{
                            failure(title)
                        }
                    }
                }else{
                    GKLogin.loginOut()
                    failure(title)
                }
            }
        }else{
            failure(title)
        }
    }
    //MARK:是否需要登录 弹出询问功能（当前如果有token默认登录，但是本地无法区分当前token是否失效）
    //MARK:如果需要回执可以使用该接口 比如收藏，收藏前需要登录，登录成功后执行收藏操作可以使用该方法
    //MARK:注意循环引用
    public static func needLogin(needAlert :Bool = false, completion:@escaping ((_ success : Bool) ->())){
        if GKLogin.loginIn{
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                completion(true)
            }
        }else{
            GKLogin.needResetTokenLogin(completion: completion)
//            if needAlert {
//                ATAlertView.showAlertView(title: "当前操作需要用户登录,请登录", message:"", normals: ["取消"], hights: ["确定"]) { (title, index) in
//                    if (index > 0){
//                        BLogin.needResetTokenLogin(completion: completion)
//                    }else{
//                        completion(false)
//                    }
//                }
//            }else{
//                BLogin.needResetTokenLogin(completion: completion)
//            }
        }
    }
    //MARK:登录成功保存数据
    public static func loginSuccess(_ user :GKUser){
        GKLogin.saveData(user)
        if GKLogin.login {
            let vc = UIViewController.rootTopPresentedController()
            vc.dismiss(animated: true) {
                self.loginCompletion(true)
            }
        }
        else{
            self.loginCompletion(true)
        }
        NotificationCenter.default.post(name: loginInSuccess, object: nil, userInfo: nil)
    }
    //MARK:登录失败 用户登录失败或者点击返回
    public static func loginFailure(){
        if GKLogin.login {
            let vc : UIViewController = UIViewController.rootTopPresentedController()
            vc.dismiss(animated: true) {
                self.loginCompletion(false)
            }
        }
        else{
            self.loginCompletion(false)
        }
    }
    //MARK:登出删除数据
    public static func loginOut( ){
        GKLogin.deleteUser()
        NotificationCenter.default.post(name: loginOutSuccess, object: nil, userInfo: nil)
    }
    fileprivate static func loginCompletion(_ finish : Bool){
        guard let completion = GKLogin.manager.completion else { return }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            completion(finish)
        }
    }
    //MARK:是否需要重新登录（重新登录删除本地token）
    //MARK:注意循环引用
    fileprivate static func needResetTokenLogin(completion:@escaping ((_ success : Bool) ->())){
        GKLogin.manager.completion = completion
        GKLogin.jumpToLoginContoller()
     }
    fileprivate static func jumpToLoginContoller(){
        if GKLogin.login || GKLogin.loginIn{
            return
        }
        let vc : UIViewController = UIViewController.rootTopPresentedController()
        let login = GKLoginController()
        let nvc : BaseNavigationController = BaseNavigationController(rootViewController: login)
        login.hidesBottomBarWhenPushed = true
//        if #available(iOS 11.0, *) {
//            nvc.navigationBar.prefersLargeTitles = false
//            nvc.navigationItem.largeTitleDisplayMode = .automatic
//        } else {
//            // Fallback on earlier versions
//        }
        nvc.modalPresentationStyle = .fullScreen
        vc.present(nvc, animated: true, completion: nil)
    }
}
